import type { MaybeRefOrGetter } from "vue";

import type { MerakControlInstance, MerakControlProps, MerakControlOption } from "@/components/MerakControl";

import { getCurrentInstance, ref, reactive, toValue, computed, watch, nextTick } from "vue";

import { ResultEnum } from "@/enums/httpEnum";
import { validUid, validsku, getBrandAndColor, getOptions } from "@/api/modules/goodsArchive/addGoodsArchive";

/**
 * @param typeId 品类 ID
 * @param suite 是否套件 0: 否  1: 是
 * @param queueId 队列请求 ID
 * @param editor 表单是否编辑状态
 * @param formItems 表单控件渲染数据
 * @param formData 表单回显数据
 * @param readonlyKeys 表单只读控件字段集合
 * @param requiredKeys 表单必填控件字段集合
 * @param linkage 组件联动函数
 */
interface ProductFormProps {
  typeId: MaybeRefOrGetter<string | number>;
  suite: MaybeRefOrGetter<0 | 1>;
  queueId?: MaybeRefOrGetter<string | undefined>;
  editor?: MaybeRefOrGetter<Boolean>;
  formItems?: MaybeRefOrGetter<MerakControlProps[]>;
  formData?: MaybeRefOrGetter<Record<string, any>>;
  readonlyKeys?: MaybeRefOrGetter<Array<string>>;
  requiredKeys?: MaybeRefOrGetter<Array<string>>;
  linkage?: (field: string, value: any) => void;
}

const useProductForm = ({
  typeId,
  suite,
  queueId,
  editor,
  formItems,
  formData,
  readonlyKeys,
  requiredKeys,
  linkage
}: ProductFormProps) => {
  const currentInstance = getCurrentInstance();

  // 初始化锁
  const locked = ref(false);

  // 表单项 ref 集合
  const recombRefs = reactive<Record<string, MerakControlInstance>>({});

  // 表单数据复制
  const recombCopy = reactive<Record<string, any>>({});

  // 表单数据
  const recombValue = reactive<Record<string, any>>({});

  // 前缀集合
  const recombPrefix = reactive<Record<string, string>>({});

  // 额外选项集合
  const recombOptions = reactive<Record<string, MerakControlOption[]>>({});

  // 记录外部必填项集合
  const recombCopyKeys = reactive<Array<string>>([]);

  // 表单渲染数据
  const recombItems = computed(() => {
    return [...(toValue(formItems) ?? [])].map(formItem => {
      // 仅展示判定
      const onlyView = !!toValue(editor) ? toValue(readonlyKeys)?.some(key => formItem.field === key) : true;
      const item: MerakControlProps = { ...formItem, onlyView };
      if (item.type === "select") {
        item.async = true;
      }
      if (toValue(requiredKeys)?.includes(item.field)) {
        item.required = true;
      }
      switch (item.field) {
        // 商家名称
        case "supplier_id":
          Object.assign(item, { remote: true, placeholder: currentInstance?.proxy?.$t("goods_archive.supplier_id_placeholder") });
          break;
        // 品牌
        case "brand_id":
          // 商家选择后联动
          Object.assign(item, {
            disabled: !validValue(recombValue.supplier_id) || !recombOptions.brand_id?.length,
            options: [...(recombOptions.brand_id ?? [])]
          });
          break;
        // 系统型号
        case "spu":
          Object.assign(item, {
            maxlength: 70 - (recombPrefix.spu_prefix?.length ?? 0) - 1,
            disabled: !recombPrefix.spu_prefix,
            validValue: (value: string) => Promise.resolve(value.replace(/[^a-zA-Z0-9\-\_]/g, "")),
            tip: currentInstance?.proxy?.$t("goods_archive.spu_sku_tip")
          });
          if (!onlyView) {
            item.rules = [
              {
                required: true,
                trigger: "blur",
                validator: (rule, value, callback) => {
                  if (!value) {
                    return callback(new Error(currentInstance?.proxy?.$t("goods_archive.spu_valid")));
                  }
                  validUid(`${recombPrefix.spu_prefix}_${value}`).then(({ code, message }) => {
                    if (code == ResultEnum.SUCCESS) {
                      return callback();
                    }
                    return callback(new Error(message as string));
                  });
                }
              }
            ];
          }
          break;
        // 系统货号
        case "sku":
          Object.assign(item, {
            maxlength: 70 - (recombPrefix.spu_prefix?.length ?? 0) - 1,
            disabled: !recombPrefix.sku_prefix,
            validValue: (value: string) => Promise.resolve(value.replace(/[^a-zA-Z0-9\-\_]/g, "")),
            tip: currentInstance?.proxy?.$t("goods_archive.spu_sku_tip")
          });
          if (!onlyView) {
            item.rules = [
              {
                required: true,
                trigger: "blur",
                validator: (rule, value, callback) => {
                  if (!value) {
                    return callback(new Error(currentInstance?.proxy?.$t("goods_archive.art_valid")));
                  }
                  validsku(`${recombPrefix.sku_prefix}-${value}`).then(({ code, message }) => {
                    if (code == ResultEnum.SUCCESS) {
                      return callback();
                    }
                    return callback(new Error(message as string));
                  });
                }
              }
            ];
          }
          break;
        // 套件品类
        case "merge_category":
          item.required = !!item.required ? item.required : [3, 9].includes(Number(toValue(typeId))) && !!toValue(suite);
          break;
        // 透气孔和条带
        case "cc_shoelace":
          Object.assign(item, {
            required: !!item.required ? item.required : Number(recombValue.cc_model) === 5511,
            disabled: Number(recombValue.cc_model) !== 5511
          });
          break;
        // 鞋底加固方式
        case "cc_tread_type":
          item.required = !!item.required ? item.required : [13, 14, 15].includes(Number(recombValue.cc_goods_name));
          break;
        // 鞋跟加固方式
        case "cc_heel_height_range":
          item.required = !!item.required ? item.required : [51, 52, 53, 5509].includes(Number(recombValue.cc_shoelace));
          break;
        // 鞋筒高度范围
        case "cc_tube_height_range":
          item.required = !!item.required
            ? item.required
            : [8, 9, 10, 11, 13, 14, 15].includes(Number(recombValue.cc_goods_name));
          break;
        // 每根单丝细度
        case "cc_fineness_of_each_filament":
          item.required = !!item.required ? item.required : [862, 863, 864].includes(Number(recombValue.cc_goods_name));
          break;
        // 功率
        case "cc_power":
          item.required = !!item.required
            ? item.required
            : Number(toValue(typeId)) === 25
              ? [
                  2521, 2522, 2524, 2526, 2546, 2551, 2563, 2564, 2721, 2722, 2723, 2725, 2726, 2727, 2728, 2729, 2730, 2731,
                  2732, 2733, 2749, 2765, 2770, 2771, 2772, 2775, 2776, 2777, 2778, 2779, 2780, 2782, 2783
                ].includes(Number(recombValue.cc_goods_name))
              : Number(toValue(typeId)) === 37
                ? [3029, 3030, 3031, 3032, 3033, 3034, 3035, 3036, 3037, 3038].includes(Number(recombValue.cc_goods_name))
                : false;
          break;
        // 25: 电压  31: 额定电压  37: 3C
        case "cc_voltage":
          item.required = !!item.required
            ? item.required
            : Number(toValue(typeId)) === 25
              ? [
                  2521, 2522, 2524, 2526, 2546, 2551, 2563, 2564, 2721, 2722, 2723, 2725, 2726, 2727, 2728, 2729, 2730, 2731,
                  2732, 2733, 2749, 2765, 2770, 2771, 2772, 2775, 2776, 2777, 2778, 2779, 2780, 2782, 2783
                ].includes(Number(recombValue.cc_goods_name))
              : Number(toValue(typeId)) === 31
                ? Number(recombValue.cc_goods_name) === 2849
                : Number(toValue(typeId)) === 37
                  ? [3033, 3034].includes(Number(recombValue.cc_goods_name))
                  : false;
          break;
        // 集尘袋容积
        case "cc_dust_bag_volume":
          item.required = !!item.required ? item.required : [2521, 2522].includes(Number(recombValue.cc_goods_name));
          break;
        // 适用面积
        case "cc_area":
          item.required = !!item.required ? item.required : [2546].includes(Number(recombValue.cc_goods_name));
          break;
        // 外壳材质
        case "cc_shell_material":
          item.required = !!item.required ? item.required : [2527, 2547].includes(Number(recombValue.cc_goods_name));
          break;
        // 是否带麦克风
        case "cc_microphone":
        // 是否带蓝牙
        case "cc_bluetooth":
        // 频率范围
        case "cc_frequency_range":
          item.required = !!item.required ? item.required : [3029, 3030, 3031, 3032].includes(Number(recombValue.cc_goods_name));
          break;
        // 接口类型
        case "cc_interface_type":
          item.required = !!item.required ? item.required : [3033, 3034].includes(Number(recombValue.cc_goods_name));
          break;
        // 输入电压
        case "cc_input_voltage":
        // 输出电压
        case "cc_output_voltage":
          item.required = !!item.required ? item.required : [3035, 3036, 3037, 3038].includes(Number(recombValue.cc_goods_name));
          break;
        // 数据线长
        case "cc_length_data_wire":
          item.required = !!item.required ? item.required : [3029, 3033, 3034].includes(Number(recombValue.cc_goods_name));
          break;
        // 详细材质
        case "cc_material_detail":
          item.required = !!item.required
            ? item.required
            : [3035, 3036, 3037, 3038, 3039, 3040, 3041, 3042].includes(Number(recombValue.cc_goods_name));
          break;
        // 是否装软垫
        case "cc_upholstered":
        // 座面材质
        case "cc_seat_material":
          item.required = !!item.required
            ? item.required
            : Number(toValue(typeId)) === 38
              ? Number(recombValue.cc_catalog) === 2984
              : Number(toValue(typeId)) === 40
                ? Number(recombValue.cc_catalog) === 3276
                : false;
          break;
        // 框架材质
        case "cc_frame_material":
          item.required = !!item.required
            ? item.required
            : Number(toValue(typeId)) === 35
              ? Number(recombValue.cc_goods_name) === 2917
              : Number(toValue(typeId)) === 38
                ? Number(recombValue.cc_catalog) === 2984
                : Number(toValue(typeId)) === 40
                  ? Number(recombValue.cc_catalog) === 3276
                  : false;
          break;
        // 应用场景
        case "cc_place":
        // 高度
        case "cc_height":
          item.required = !!item.required
            ? item.required
            : Number(toValue(typeId)) === 38
              ? Number(recombValue.cc_catalog) === 2986
              : Number(toValue(typeId)) === 40
                ? Number(recombValue.cc_catalog) === 3277
                : false;
          break;
        // 宽度
        case "cc_width":
        // 长度
        case "cc_length":
          item.required = !!item.required
            ? item.required
            : Number(toValue(typeId)) === 38
              ? Number(recombValue.cc_goods_name) === 3084
              : Number(toValue(typeId)) === 40
                ? Number(recombValue.cc_goods_name) === 3279
                : false;
          break;
        // 头围
        case "cc_head_circum":
          item.required = !!item.required ? item.required : [4697, 4699].includes(Number(recombValue.cc_for_age));
          break;
        // 铲斗类型
        case "cc_shovel_type":
        // 传动方式
        case "cc_transfer_method":
        // 使用年限
        case "cc_working_hours_from_release":
          item.required = !!item.required ? item.required : [5307, 5308, 5309].includes(Number(recombValue.cc_goods_name));
          break;
        // 车把材质
        case "handle_material":
        // 板面材质
        case "desk_material":
        // 刹车类型
        case "brake_type":
        // 把手可调档位
        case "handle_positions":
        // 把手高度(cm)
        case "handle_height":
          item.required = !!item.required ? item.required : Number(recombValue.category) === 4881;
          break;
        // 座椅可调档位
        case "chair_positions":
          item.required = !!item.required ? item.required : Number(recombValue.category) === 4879;
          break;
        // 游戏板
        case "game_panel":
        // 音乐效果
        case "sound_effects":
        // 灯光效果
        case "light_effects":
        // 电池
        case "battery":
          item.required = !!item.required ? item.required : [4879, 4880].includes(Number(recombValue.category));
          break;
        default:
          break;
      }
      return item;
    });
  });

  // 表单控件选项请求
  const recombQueryOptions: MerakControlInstance["queryOptions"] = (field: string) => {
    if (["brand_id"].includes(field)) return Promise.resolve();
    return new Promise<MerakControlOption[]>(resolve => {
      getOptions(toValue(typeId), field, toValue(suite), toValue(queueId)).then(({ code, data }) => {
        if (code == ResultEnum.SUCCESS) {
          resolve(data);
        }
      });
    });
  };

  // 表单控件触发事件
  const recombChange = (field: string, value: any, options?: MerakControlOption[], auto?: boolean) => {
    console.log(field, value, options, auto);
    const changeMap: Record<string, () => void> = {
      // 商家
      supplier_id: () => {
        if (!auto) {
          recombRefs.brand_id?.resetField(true);
          recombRefs.spu?.resetField(true);
          recombRefs.spu?.validate("blur");
          recombRefs.sku?.resetField(true);
          recombRefs.sku?.validate("blur");
        }
        if (!validValue(value)) {
          if (recombItems.value.some(item => item.field === "spu")) {
            delete recombPrefix.spu_prefix;
          } else if (recombItems.value.some(item => item.field === "sku")) {
            delete recombPrefix.sku_prefix;
          }
          return;
        }
        getBrandAndColor(toValue(typeId), value, toValue(queueId)).then(({ code, data }) => {
          if (code == ResultEnum.SUCCESS) {
            if (recombItems.value.some(item => item.field === "spu")) {
              recombPrefix.spu_prefix = data.qf_code;
            } else if (recombItems.value.some(item => item.field === "sku")) {
              recombPrefix.sku_prefix = data.qf_code;
            }
            recombOptions.brand_id = data.brand;
            linkage?.("color", data.color);
          }
        });
      },
      // 系统型号
      spu: () => {
        if (!recombPrefix.spu_prefix) return;
        recombValue.spu_txt = `${recombPrefix.spu_prefix}_${recombValue.spu}`;
        linkage?.("spu", recombValue.spu_txt);
      },
      // 系统货号
      sku: () => {
        if (!recombPrefix.sku_prefix) return;
        recombValue.sku_txt = `${recombPrefix.sku_prefix}_${recombValue.sku}`;
        linkage?.("spu", recombValue.sku_txt);
      },
      // 性别
      gender: () => {
        if (!auto) {
          if ([6923, 6924].includes(Number(value)) && recombValue.size_standard !== 2775) {
            recombRefs.size_standard?.resetField(true);
          }
        }
        recombResetLinkage(field);
      },
      // 合并属性
      merge_material_plus: () => {
        const option = recombRefs.merge_material_plus?.options?.find(option => option.value === recombValue.merge_material_plus);
        if (!!option) {
          recombValue.cc_material_plus = option.cc_material_plus;
          recombValue.material_plus = option.material_plus;
        }
      },
      // 码制选择
      size_standard: () => {
        linkage?.("size", Number(value));
      },
      // 货品分类
      cc_catalog: () => {
        if (!auto) {
          recombRefs.cc_material_lining?.resetField(true);
          recombRefs.cc_tube_height_range?.resetField(true);
          recombRefs.cc_upholstered?.validate();
          recombRefs.cc_frame_material?.validate();
          recombRefs.cc_seat_material?.validate();
          recombRefs.cc_place?.validate();
          recombRefs.cc_height?.validate();
        }
        recombResetLinkage(field);
        // 额外处理鞋筒高度
        recombResetLinkage("cc_tube_height_range");
      },
      // 俄罗斯国家标准品名
      cc_goods_name: () => {
        if (!auto) {
          recombRefs.cc_tube_height_range?.resetField(true);
          recombRefs.cc_tread_type?.validate();
          recombRefs.cc_tube_height_range?.validate();
          recombRefs.cc_fineness_of_each_filament?.validate();
          recombRefs.cc_power?.validate();
          recombRefs.cc_voltage?.validate();
          recombRefs.cc_dust_bag_volume?.validate();
          recombRefs.cc_area?.validate();
          recombRefs.cc_shell_material?.validate();
          recombRefs.cc_microphone?.validate();
          recombRefs.cc_bluetooth?.validate();
          recombRefs.cc_frequency_range?.validate();
          recombRefs.cc_interface_type?.validate();
          recombRefs.cc_input_voltage?.validate();
          recombRefs.cc_output_voltage?.validate();
          recombRefs.cc_length_data_wire?.validate();
          recombRefs.cc_material_detail?.validate();
          recombRefs.cc_width?.validate();
          recombRefs.cc_length?.validate();
          recombRefs.cc_shovel_type?.validate();
          recombRefs.cc_transfer_method?.validate();
          recombRefs.cc_working_hours_from_release?.validate();
          nextTick(() => {
            recombRefs.cc_density?.validate();
            recombRefs.cc_number_of_sheets?.validate();
          });
        }
        recombResetLinkage(field);
        // 额外处理鞋筒高度
        recombResetLinkage("cc_tube_height_range");
      },
      // 款式
      cc_model: () => {
        if (!auto) {
          recombRefs.cc_shoelace?.resetField(true);
          recombRefs.cc_shoelace?.validate();
        }
      },
      // 透气孔和条带信息
      cc_shoelace: () => {
        if (!auto) {
          recombRefs.cc_heel_height_range?.validate();
        }
      },
      // 清关填充物
      cc_filling: () => {
        if (!auto) {
          nextTick(() => {
            recombRefs.cc_process?.validate();
            recombRefs.cc_processing_technology?.validate();
          });
        }
        recombResetLinkage(field);
      },
      // 性别
      merge_gender: () => {
        recombResetLinkage(field);
      },
      // 适用年龄
      cc_for_age: () => {
        if (!auto) {
          recombRefs.cc_head_circum?.validate();
        }
      },
      // 销售品类
      category: () => {
        if (!auto) {
          recombRefs.handle_material?.validate();
          recombRefs.desk_material?.validate();
          recombRefs.brake_type?.validate();
          recombRefs.handle_positions?.validate();
          recombRefs.handle_height?.validate();
          recombRefs.chair_positions?.validate();
          recombRefs.game_panel?.validate();
          recombRefs.sound_effects?.validate();
          recombRefs.light_effects?.validate();
          recombRefs.battery?.validate();
        }
      }
    };
    // 等待双向绑定更新
    nextTick(() => {
      changeMap[field]?.();
      if (!!options) {
        const option = options.find(option => option.value === value);
        recombValue[`${field}_txt`] = option?.label;
      }
    });
  };

  /**
   * 重置表单联动
   * 多数情况下用于禁用选项
   * @param field 表单项字段键名
   */
  const recombResetLinkage = (field?: string) => {
    const resetLinkageMap: Record<string, () => void> = {
      // 性别
      gender: () => {
        recombRefs.size_standard?.disableInvertOptions([6923, 6924].includes(Number(recombValue.gender)) ? [2775] : []);
      },
      // 货品分类
      cc_catalog: () => {
        recombRefs.cc_material_lining?.disableInvertOptions(
          [3, 4].includes(Number(recombValue.cc_catalog)) ? [32, 33, 35, 534] : []
        );
      },
      // 俄罗斯国家标准品名
      cc_goods_name: () => {
        if (!validValue(recombValue.cc_goods_name)) return;
        switch (Number(toValue(typeId))) {
          case 28:
            linkage?.("paper", Number(recombValue.cc_goods_name));
            break;
          default:
            break;
        }
      },
      // 鞋筒高度范围
      cc_tube_height_range: () => {
        recombRefs.cc_tube_height_range?.disableOptions([]);
        if (![1, 2].includes(Number(recombValue.cc_catalog))) return;
        switch (Number(recombValue.cc_goods_name)) {
          case 8:
            recombRefs.cc_tube_height_range?.disableOptions([847]);
            break;
          case 9:
          case 10:
          case 13:
            recombRefs.cc_tube_height_range?.disableOptions([846]);
            break;
          case 11:
          case 14:
            recombRefs.cc_tube_height_range?.disableOptions([845]);
            break;
          case 15:
            recombRefs.cc_tube_height_range?.disableOptions([848]);
            break;
          default:
            break;
        }
      },
      // 清关填充物
      cc_filling: () => {
        if (!validValue(recombValue.cc_filling)) return;
        linkage?.("filling", Number(recombValue.cc_filling));
      },
      // 合并属性性别
      merge_gender: () => {
        if (!validValue(recombValue.merge_gender)) return;
        linkage?.("gender", Number(recombValue.merge_gender));
      }
    };
    if (!!field) {
      resetLinkageMap[field]?.();
    } else {
      recombItems.value.map(item => {
        resetLinkageMap[item.field]?.();
      });
    }
  };

  // 记录数据
  const recombRecord = () => {
    Object.keys(recombCopy).forEach(key => {
      delete recombCopy[key];
    });
    Object.assign(recombCopy, recombValue);
    return Promise.resolve();
  };

  // 还原数据
  const recombReduction = () => {
    Object.keys(recombValue).forEach(key => {
      delete recombValue[key];
    });
    Object.assign(recombValue, recombCopy);
    recombResetLinkage();
    return Promise.resolve();
  };

  // 验证数据
  const validValue = (value: any) => typeof value === "number" || !!value;

  // 初始化数据
  watch(
    () => toValue(formData),
    value => {
      if (!value) return;
      Object.keys(value)
        .filter(key => recombItems.value.some(item => key.includes(item.field)))
        .forEach(key => {
          recombValue[key] = value[key];
        });
      if (locked.value) return;
      locked.value = true;
      recombItems.value.forEach(item => {
        if (validValue(value[item.field])) {
          recombChange(item.field, recombValue[item.field], recombRefs[item.field]?.options, true);
        }
      });
      if (!value.qf_code) return;
      // 系统型号/货号
      if (toValue(formItems)?.some(item => item.field === "spu")) {
        recombValue.spu_txt = `${value.qf_code}_${recombValue.spu}`;
      } else if (toValue(formItems)?.some(item => item.field === "sku")) {
        recombValue.sku_txt = `${value.qf_code}_${recombValue.sku}`;
      }
    },
    { immediate: true, deep: true }
  );

  // 清除验证
  watch(
    () => toValue(requiredKeys),
    value => {
      if (value?.length === 0) {
        recombCopyKeys.forEach(key => {
          nextTick(() => {
            recombRefs[key]?.clearValidate();
          });
        });
      } else {
        recombCopyKeys.length = 0;
        recombCopyKeys.push(...[...(value ?? [])]);
      }
    },
    { deep: true }
  );

  return {
    recombRefs,
    recombValue,
    recombPrefix,
    recombItems,
    recombChange,
    recombQueryOptions,
    recombRecord,
    recombReduction,
    validValue
  };
};

export default useProductForm;
